﻿using System;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Http;
using Newtonsoft.Json;
using FytSoa.Common;

namespace FytSoa.Extensions
{
    /// <summary>
    /// 阿里云短信平台
    /// </summary>
    public class AliSsmTool
    {
        /// <summary>
        /// 发送短信-验证码
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static AliSsmRes SendSsm(AliSsmParam param)
        {
            var res = new AliSsmRes();
            var accessKey = ConfigExtensions.Configuration["AliSsm:accessKey"];
            var accessSecret = ConfigExtensions.Configuration["AliSsm:accessSecret"];
            try
            {
                IClientProfile profile = DefaultProfile.GetProfile("default", accessKey, accessSecret);
                DefaultAcsClient client = new DefaultAcsClient(profile);
                CommonRequest request = new CommonRequest();
                request.Method = MethodType.POST;
                request.Domain = "dysmsapi.aliyuncs.com";
                request.Version = "2017-05-25";
                request.Action = "SendSms";
                // request.Protocol = ProtocolType.HTTP;
                request.AddQueryParameters("PhoneNumbers", param.phone);
                request.AddQueryParameters("SignName", param.sign);
                request.AddQueryParameters("TemplateCode", param.tempId);
                request.AddQueryParameters("TemplateParam", "{code:'" + param.code + "'}");
                CommonResponse response = client.GetCommonResponse(request);
                res = JsonConvert.DeserializeObject<AliSsmRes>(System.Text.Encoding.Default.GetString(response.HttpResponse.Content));
            }
            catch (Exception ex)
            {
                res.Code = "error";
                res.Message = ex.Message;
            }
            return res;
        }
    }

    /// <summary>
    /// 短息参数
    /// </summary>
    public class AliSsmParam
    {
        /// <summary>
        /// 手机号码
        /// </summary>
        public string phone { get; set; }

        /// <summary>
        /// 验证码
        /// </summary>
        public string code { get; set; }

        /// <summary>
        /// 签名
        /// </summary>
        public string sign { get; set; } = "都港航空";

        /// <summary>
        /// 模板ID
        /// </summary>
        public string tempId { get; set; }
    }

    /// <summary>
    /// 短信返回参数
    /// </summary>
    public class AliSsmRes
    {
        public string Message { get; set; }

        public string RequestId { get; set; }

        public string BizId { get; set; }

        /// <summary>
        /// 返回OK代表请求成功
        /// </summary>
        public string Code { get; set; }
    }
}
